const koa = require("koa"),
  server = new koa(), // app.context 这是给整个koa的ctx添加属性，方便中间件中调用
  router = require("koa-router")(), // https://github.com/ZijianHe/koa-router
  path = require("path");
const PORT = 3000; // 启动的端口
const log = require("./log"); // 日志打印
const koaStatic = require("koa-static");
const koaMount = require("koa-mount");
const $router = require("./server/router");
const resolve = file => path.resolve(__dirname, file);
const JWT = require("./server/common/JWT");
// 开放目录
server.use(koaMount("/dist", koaStatic(resolve("./dist"))));
server.use(koaMount("/public", koaStatic(resolve("./public"))));

router.use("", $router.routes());
server
  // 拦截登陆
  .use(async (ctx, next) => {
    // 路由拦截
    // 验证用户是否登陆
    const { request, cookies } = ctx;
    const url = request.url;
    // 不是静态文件，不是登陆页面
    if (!url.includes(".") && ["/"].indexOf(request.url) === -1) {
      // 拦截页面和请求
      const token = cookies.get("Admin-Token");
      if (token) {
        // 有 token 信息
        try {
          // 解码过程可能会发生意外
          const result = JWT.verify(token);
          const currentDateTime = Math.floor(Date.now() / 1000);
          if (currentDateTime > result.iat + JWT.expires) {
            // 登录过期
            ctx.$isLogin = false;
          } else {
            // 解析成功，并且还未过期
            ctx.$token = token;
          }
        } catch (e) {
          // 发生异常，token 是无效的，JWT 解析失败了
          ctx.$isLogin = false;
        }
      } else {
        // 无 token 信息
        ctx.$isLogin = false;
      }
    }
    await next();
  })
  .use(router.routes())
  .use(router.allowedMethods())
  .listen(PORT, log(`server start success: http://127.0.0.1:${PORT}`));

// 异常守护
process.on("uncaughtException", function(err) {
  console.log("Caught exception: " + err);
});
